<template autoRoute="true">
  <div class="field-container">
    <section class="top">
      <div class="title">项目模版</div>
      <div style="display: flex; gap: 12px">
        <el-input
          v-model="searchName"
          class="responsive-input"
          placeholder="请输入名称搜索"
          :prefix-icon="Search"
          @change="handleSearch"
        />
        <el-button @click="handleAddTemp" type="primary" :icon="Plus"
          >添加</el-button
        >
      </div>
    </section>
    <el-alert
      title="项目字段管理用于配置项目需要的显示字段，配置完成后需和项目类型进行关联，配置后对后续使用该项目类型的项目生效。"
      type="warning"
      show-icon
      class="topAlert"
    />
    <div class="wbs-tree-container">
      <!-- 批量操作浮层 -->
      <CLBatchOpToolbar
        :show="showCLBatchOpToolbar"
        :selected-count="selectedRecords.length"
        @delete="handleBatchDelete"
      ></CLBatchOpToolbar>
      <!--   表格   -->
      <CLTable
        v-loading="loading"
        :fields="fields"
        :router-fields="['statusFlag']"
        :initial-data="tableData"
        :line-height="currentLineHeight"
        :more-actions="moreActions"
        :tableConfig="tableConfig"
        :page-query="tableDataQuery"
        @pagerChange="pagerChange"
        @onMoreAction="handleMoreAction"
        @show:records="handleShowRecords"
      >
      </CLTable>
      <!-- 字段配置悬浮层 -->
      <FieldConfigPopup
        :fields="currentFields"
        :position="fieldConfigPosition"
        :visible="showFieldConfig"
        @close="showFieldConfig = false"
        @fieldsChange="handleFieldsChange"
      />
    </div>
    <CDialog
      :title="operate === 'create' ? '新建' : '编辑'"
      v-model="dialogVisible"
      @handleDialogOk="handleCreateOrEdit"
      :fields="dialogFields"
      :nodeData="selectedNode"
    ></CDialog>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, provide } from "vue";
  import { Plus, Search } from "@element-plus/icons-vue";
  import { tableFields, dialogCreateOrEditFields } from "./fields/index.ts";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import CLTable from "@/components/CLTable/index.vue";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import type { pagerListQueryType } from "@/interface/common.ts";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import {
    createPmTemp,
    getPmTempList,
    deletePmTemp,
    getPmTempInfo,
    updatePmTemp,
  } from "@/api/pm/pmTemplate.ts";
  import type { pmTemplateVORes } from "@/interface/pm/pmTemplate.ts";
  import { projectListAJAX } from "@/api/pm/member.ts";
  import CDialog from "@/components/CDialog.vue";
  import { deepCopy } from "@/utils/common.ts";
  import { useRouter } from "vue-router";

  const router = useRouter();
  const searchName = ref("");

  const dialogFields = ref<DynamicField[]>(dialogCreateOrEditFields);

  // 批量操作
  const showCLBatchOpToolbar = ref(false);
  const selectedRecords = ref<pmTemplateVORes[]>([]);
  // 处理批量删除操作
  const handleBatchDelete = () => {
    console.log("selectedRecords", selectedRecords.value);
    if (selectedRecords.value.length === 0) return;
    ElMessageBox.confirm("确定删除该任务类型?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      // type: "warning",
      draggable: true,
    })
      .then(async () => {})
      .catch(() => {});
    // 删除完成后清空选中状态
  };

  // 表格
  const loading = ref(false);
  const tableDataQuery = reactive<pagerListQueryType>({
    pageNo: 1,
    pageSize: 10,
    conditions: [],
    total: 0,
  });
  const fields = ref<DynamicField[]>(tableFields); // table表格展示列
  const tableData = ref<pmTemplateVORes[]>([]);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );
  const moreActions = ref([
    { key: "setting", label: "配置模板" },
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
  ]);
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 135px)",
    showOperationsColumn: true, // 是否显示操作列
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: 140, //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: true,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    // rowSeriesNumber: {
    //   dragOrder: true, // 开启行号拖拽排序
    // },
    // borderMode: "none", // 表格边框模式，none为无边框
  });

  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableDataQuery.pageNo = pager.currentPage;
    tableDataQuery.pageSize = pager.pageSize;
    getPmTemplateList();
  };

  const handleSearch = () => {
    tableDataQuery.conditions.push({
      field: "name",
      operator: "like",
      value: searchName.value,
    });
    getPmTemplateList();
  };

  const handleMoreAction = async (action: string, node: any) => {
    if (action === "edit") {
      selectedNode.value = deepCopy(node);
      selectedNode.value.name = selectedNode.value.name.zh_CN;
      dialogVisible.value = true;
      operate.value = "edit";
    } else if (action === "delete") {
      ElMessageBox.confirm("确定删除该项目模板?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      })
        .then(async () => {
          const res = await deletePmTemp(node.id);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getPmTemplateList();
        })
        .catch(() => {});
    } else if (action === "setting") {
      router.push(
        `/pm/globalSetting/pmTemplateDetail?name=${node.name.zh_CN}&id=${node.id}`,
      );
    } else if (action === "statusFlag") {
      loading.value = true;
      const params: pmTemplateVORes = {
        id: node.id,
        status: node.status === "NORMAL" ? "DISABLE" : "NORMAL",
      };
      await updatePmTemp(params);
      loading.value = false;
      ElMessage({
        type: "success",
        message: "更新成功",
      });
      dialogVisible.value = false;
      getPmTemplateList();
    }
  };
  const handleShowRecords = (records: any[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
  };

  // 配置字段
  const currentFields = ref<DynamicField[]>([]);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const showFieldConfig = ref(false);

  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  // const addRecord = (newRecords: ProjectNode[]) => {
  //   tableData.value = [...newRecords];
  // };
  //
  // // 提供给所有子孙组件使用
  // provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  const getPmTemplateList = async () => {
    loading.value = true;
    const res = await getPmTempList(tableDataQuery);
    tableDataQuery.total = res.total;
    tableData.value =
      res.result?.map((item) => {
        item.useCount = item.childProjectIdList?.length || "0";
        item.statusFlag = item.status === "NORMAL";
        return item;
      }) || [];
    tableDataQuery.conditions = [];
    loading.value = false;
  };

  const getProjectList = async () => {
    const res = await projectListAJAX({
      pageNo: 1,
      pageSize: 998,
      conditions: [],
    });
    dialogFields.value.forEach((item) => {
      if (item.field === "projectId") {
        item.options = res.result.map((item) => {
          return {
            label: item.name.zh_CN,
            value: item.id,
          };
        });
      }
    });
    console.log(res);
  };
  const dialogVisible = ref(false);
  const operate = ref("create");
  const selectedNode = ref<any>({});

  const handleCreateOrEdit = async (formData: Record<string, any>) => {
    console.log(formData, "handleCreateLifecycle");
    if (operate.value === "create") {
      const params: pmTemplateVORes = {
        name: {
          zh_CN: formData.name,
        },
        remark: formData.remark,
        projectId: formData.projectId,
        status: formData.status,
      };
      await createPmTemp(params);
      ElMessage({
        type: "success",
        message: "创建成功",
      });
      dialogVisible.value = false;
      getPmTemplateList();
    } else if (operate.value === "edit") {
      const params: pmTemplateVORes = {
        id: formData.id,
        name: {
          zh_CN: formData.name,
        },
        remark: formData.remark,
        projectId: formData.projectId,
        status: formData.status,
      };
      await updatePmTemp(params);
      ElMessage({
        type: "success",
        message: "编辑成功",
      });
      dialogVisible.value = false;
      getPmTemplateList();
    }
  };

  const handleAddTemp = () => {
    dialogVisible.value = true;
    operate.value = "create";
  };
  onMounted(() => {
    getProjectList();
    getPmTemplateList();
  });
</script>

<style scoped lang="scss">
  .table-container {
    margin-top: 12px;
    height: calc(100vh - 180px);
  }

  .field-container {
    padding: 16px;
  }
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-weight: 500;
      font-size: 18px;
      line-height: 22px;
    }
  }

  .topAlert {
    margin-top: 12px;
    padding: 4px 12px;
    :deep(.el-alert__close-btn) {
      top: 8px;
      color: #1f2329;
    }
  }
</style>
